package com.yhp.web;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yhp.bean.Menu;
import com.yhp.bean.Role;
import com.yhp.bean.dto.MenuDTO;
import com.yhp.service.MenuService;
import com.yhp.service.RoleService;
import com.yhp.service.impl.MenuServiceImpl;
import com.yhp.service.impl.RoleServiceImpl;
import com.yhp.util.PageUtil;

/**
 * 角色 servlet
 *
 * @author bing.zhang06@hand-china.com 2021/7/31 15:55
 **/
@WebServlet(urlPatterns = {"/power/role/roles"})
public class RoleServlet extends HttpServlet {
    private RoleService roleService = new RoleServiceImpl();
    private MenuService menuService = new MenuServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("select".equals(method)) {
            select(req, resp);
        } else if ("selectmenus".equals(method)) {
            selectmenus(req, resp);
        } else if ("insert".equals(method)) {
            insert(req, resp);
        } else if ("findByRoleId".equals(method)) {
            findByRoleId(req, resp);
        }
    }

    protected void findByRoleId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer roleId = Integer.valueOf(req.getParameter("roleId"));

        // 1.获取当前角色信息(包括菜单)
        Role role = roleService.findById(roleId);
        req.setAttribute("role", role);
        // 2.获取系统菜单
        List<Menu> menuList = menuService.getMenuList();
        // 3.处理当前角色选中的菜单
        List<MenuDTO> menuDTOS = menuList.stream()
                .map(menu -> new MenuDTO(menu)).collect(Collectors.toList());

        Set<Integer> roleMenuIds = new HashSet<>();
        for (Menu menu : role.getMenuList()) {
            roleMenuIds.add(menu.getMenuId());
            for (Menu menu1 : menu.getSecondMenuList()) {
                roleMenuIds.add(menu1.getMenuId());
            }
        }

        for (MenuDTO menuDTO : menuDTOS) {
            if (roleMenuIds.contains(menuDTO.getMenuId())) {
                System.out.println("checked " + menuDTO.getMenuName());
                menuDTO.setChecked(true);
            }
            for (MenuDTO menuDTO1 : menuDTO.getSecondMenuList()) {
                if (roleMenuIds.contains(menuDTO1.getMenuId())) {
                    System.out.println("checked1 " + menuDTO1.getMenuName());
                    menuDTO1.setChecked(true);
                }
            }
        }

        // 4.返回结果
        req.setAttribute("menuDTOS", menuDTOS);
        req.getRequestDispatcher("edit.jsp").forward(req, resp);
    }

    //新增角色
    protected void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String rolename = req.getParameter("rolename");
        String state = req.getParameter("state");
        String[] menuids = req.getParameterValues("menuid");
        int i = roleService.insertRole(rolename, state, menuids);
        if (i > 0) {
            resp.sendRedirect("/power/role/roles?method=select");
        } else {
            resp.sendRedirect("/power/role/roles?method=selectmenus");
        }

    }

    //查询菜单列表
    protected void selectmenus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数
        //2.调取service方法
        List<Menu> menuList = menuService.getMenuList();
        req.setAttribute("menulist", menuList);
        req.getRequestDispatcher("add.jsp").forward(req, resp);
    }


    //查询数据（分页）
    protected void select(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数(分页参数+模糊查参数)
        String index = req.getParameter("index");
        int pageIndex = (index == null || index.length() == 0) ? 1 : Integer.parseInt(index);
        //2.调取service方法(1.查询数据列表的方法  2.查询总条数的方法)
        PageUtil pageUtil = new PageUtil();
        List<Role> roleList = roleService.getRoleList(pageIndex, pageUtil.getPageSize());
        int total = roleService.total();
        pageUtil.setTotal(total);
        pageUtil.setPageIndex(pageIndex);
        pageUtil.setDataList(roleList);

        //3.存值跳页面
        req.setAttribute("pi", pageUtil);
        req.getRequestDispatcher("list.jsp").forward(req, resp);
    }
}
